<?php
session_start();

if(!isset($_SESSION['session_key'])):

    if(isset($_POST['email']) && isset($_POST['password'])):
        global $db;

        $email = mysqli_real_escape_string($db, $_POST['email']);
        $password = md5($_POST['password']);
        
        $query = 'SELECT ID, Level FROM USERS WHERE `Email`="'.$email.'" AND `Password`="'.$password.'"';
        $result = $db->query($query);
        $isUser = $result->num_rows;

        if($isUser){
            $user = $result->fetch_assoc();
            $_SESSION['session_key'] = $user['ID'];

            if($user['Level'] == 1)
                header('Location: /msc-admin/');
            else
                header('Location: /msc-admin/login.php?status=failed');
        }
        header('Location: /msc-admin/login.php?status=failed');
    endif;

else:
    $user = $_SESSION['session_key'];
    global $db;

    $query = 'SELECT Level FROM USERS WHERE `ID`='.$user;
    $result = $db->query($query); 
    $isUser = $result->num_rows;
    if($isUser){
        $user = $result->fetch_assoc();
        if($user['Level'] == 1)
            header('Location: /msc-admin/');
        else
            header('Location: /msc-admin/login.php?status=failed');
    }else{
         header('Location: /msc-admin/login.php?status=failed');
    }

endif;

?>